package scuba.DiveBuddy.Fragments;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.DatePicker;
import org.joda.time.DateTime;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by Alexander Anderson on 12/02/14.
 */
public class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    public interface DateSetListener {
        public void onDateSet(DialogFragment fragment, DateTime date);
    }

    private Date SelectedDate;
    public Date getSelectedDate() { return SelectedDate; }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        // Create a new instance of TimePickerDialog and return it

        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        DateSetListener mListener;
        try {
            mListener = (DateSetListener)activity;
        }
        catch(ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement DateSetListener");
        }
    }

    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        // Do something with the time chosen by the user

        Calendar c = Calendar.getInstance();
        c.set(year, monthOfYear - 1, dayOfMonth, 0, 0);
        SelectedDate = c.getTime();
        ((DateSetListener)getActivity()).onDateSet(this, new DateTime(SelectedDate));
    }
}
